import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {query} from "./actions";
import {query as moneyQuery} from "../orderProfit/actions";
import {Column} from '@ant-design/plots';
import {getCurrentOrganization, getLastFilter} from "../../lib/identity";
import moment from "moment";
import {Button, Card, notification} from "antd";
import lodash from 'lodash';
import {groupBy} from "../../lib/func";

const LAST_FILTER = "orderCountLine";

class List extends PureComponent {

    componentWillMount() {
        const {dispatch} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({
            ...fields,
            'year': moment().year().toString(),
            type: '1',
            "organizationId": getCurrentOrganization()
        }));
        dispatch(moneyQuery({
            ...fields,
            'year': moment().year().toString(),
            type: '1',
            "organizationId": getCurrentOrganization()
        }));
    };

    exportFile = (fileName, fileData) => {
        document.getElementById("fileName").value = fileName;
        if (fileData && fileData.length > 0) {
            const headers = [];
            fileData.forEach(item => {
                for (let key in item) {
                    if (headers.indexOf(key) <= -1) {
                        headers.push(key);
                    }
                }
            });
            document.getElementById("headers").value = lodash.join(headers, ',');
            document.getElementById("rows").value = JSON.stringify(fileData);
            document.getElementById("exportFile").submit();
            notification.success({
                message: '请等待文件导出'
            });
        } else {
            notification.error({
                message: '没有数据可以导出'
            });
        }
    };


    render() {
        const {
            dataSource, projectData
        } = this.props;
        const data = [];
        dataSource.forEach(item => {
            const endList = item['endList'];
            endList.forEach(endItem => {
                data.push({
                    startPlace: item.startPlace, name: endItem.name, count: endItem.count
                });
            });
        });
        const config = {
            data, xField: 'name', yField: 'count', seriesField: 'startPlace', isGroup: true, columnStyle: {
                radius: [20, 20, 0, 0],
            },
        };
        const projectConfigData = [];
        const groupData = groupBy(projectData, (link) => {
            return link.clientId
        });
        for (let clientId in groupData) {
            // 1 代表是总计，总计不要
            if ("1" === clientId) {
                continue;
            }
            const dataList = groupData[clientId];
            //  取第一个
            const firstData = dataList[0];
            const found = projectConfigData.find(o => o.clientId === firstData.clientId);
            if (!found) {
                // 保存2位小数
                firstData.currentAssets = lodash.round(firstData.currentAssets, 2);
                projectConfigData.push({'name': firstData.client, "currentAssets": firstData.currentAssets})
            }
        }
        const projectConfig = {
            data: projectConfigData,
            xField: 'name',
            yField: 'currentAssets',
            label: {
                // 可手动配置 label 数据标签位置
                position: 'middle',
                // 'top', 'bottom', 'middle',
                // 配置样式
                style: {
                    fill: '#FFFFFF',
                    opacity: 0.6,
                },
            },
            xAxis: {
                label: {
                    autoHide: true,
                    autoRotate: false,
                },
            },
            meta: {
                name: {
                    alias: '客户',
                },
                currentAssets: {
                    alias: '总利润',
                },
            }
        };

        return (<div>
            <Card title="业务单量 单位：票" extra={<Button onClick={() => this.exportFile("业务单量", data)}>导出</Button>}>
                <Column {...config} />
            </Card>
            <Card title="项目数据  单位：RMB"
                  extra={<Button onClick={() => this.exportFile("项目数据", projectConfigData)}>导出</Button>}>
                <Column {...projectConfig} />
            </Card>
            <form
                id="exportFile"
                method="post"
                target="_blank"
                action="/api/orderAnalysis/commonExport"
            >
                <input
                    id="fileName"
                    name="fileName"
                    type="hidden"
                />
                <input
                    id="rows"
                    name="rows"
                    type="hidden"
                />
                <input
                    id="headers"
                    name="headers"
                    type="hidden"
                />
            </form>
        </div>);
    }
}

const mapStateToProps = state => {
    return {
        ...state.orderCountLine.list, projectData: state.orderProfit.list.dataSource
    };
};

export default connect(mapStateToProps)(List);
